package com.secondhand.project.service.impl;

import com.secondhand.common.core.domain.entity.SysUser;
import com.secondhand.common.utils.SecurityUtils;
import com.secondhand.project.domain.ChatGroup;
import com.secondhand.project.mapper.ChatGroupMapper;
import com.secondhand.project.service.IChatGroupService;
import com.secondhand.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChatGroupServiceImpl implements IChatGroupService {
    @Autowired
    private ChatGroupMapper chatGroupMapper;
    @Autowired
    private ChatInfoServiceImpl chatInfoService;
    @Autowired
    private ISysUserService userService;

    @Override
    public ChatGroup selectChatGroupById(Long id) {
        return chatGroupMapper.selectChatGroupById(id);
    }

    @Override
    public List<ChatGroup> selectChatGroupList(ChatGroup chatGroup) {
        return chatGroupMapper.selectChatGroupList(chatGroup);
    }

    public List<ChatGroup> selectUserGroup() {
        List<ChatGroup> chatGroupList = new ArrayList<>();
        Long userId = SecurityUtils.getUserId();
        List<ChatGroup> userChatGroupList = chatGroupMapper.selectByUserId(userId);
        for (ChatGroup chatGroup : userChatGroupList) {
            Long chatUserId = chatGroup.getChatUserId();
            Long num = chatInfoService.selectUnReadChatNum(userId, chatUserId);
            chatGroup.setChatNum(num);
            SysUser chatUser = userService.selectUserById(chatUserId);
            chatGroup.setChatUserName(chatUser.getNickName());
            chatGroup.setChatUserAvatar(chatUser.getAvatar());
            chatGroupList.add(chatGroup);
        }
        return chatGroupList;
    }

    @Override
    public int insertChatGroup(ChatGroup chatGroup) {
        chatGroup.setUserId(SecurityUtils.getUserId());
        ChatGroup dbChatGroup = chatGroupMapper.selectByChatUserIdAndUserId(chatGroup.getChatUserId(), chatGroup.getUserId());
        if (dbChatGroup == null) {
            chatGroupMapper.insertChatGroup(chatGroup);
        }
        ChatGroup dbChatGroup1 = chatGroupMapper.selectByChatUserIdAndUserId(chatGroup.getUserId(), chatGroup.getChatUserId());
        if (dbChatGroup1 == null) {
            dbChatGroup1 = new ChatGroup();
            dbChatGroup1.setChatUserId(chatGroup.getUserId());
            dbChatGroup1.setUserId(chatGroup.getChatUserId());
            chatGroupMapper.insertChatGroup(dbChatGroup1);
        }
        return 1;
    }

    @Override
    public int updateChatGroup(ChatGroup chatGroup) {
        return chatGroupMapper.updateChatGroup(chatGroup);
    }

    @Override
    public int deleteChatGroupByIds(Long[] ids) {
        return chatGroupMapper.deleteChatGroupByIds(ids);
    }

    @Override
    public int deleteChatGroupById(Long id) {
        return chatGroupMapper.deleteChatGroupById(id);
    }
}
